package definition

import (
	"fmt"

	config "gitee.com/woodpile/wgs.ths.config.go"
)

type Generator interface {
	Name() string
	Make() (Generator, error)
	Generate(*Context) error
}

type GeneratorConfig struct {
	GenRoot string `yaml:"genRoot,omitempty"`

	Plugins map[string]interface{} `yaml:"plugins,omitempty"`
}

func (*GeneratorConfig) Name() string {
	return "generator"
}

func (*GeneratorConfig) ToDefault(cfg config.IConfigDefault) {
	ac := cfg.(*GeneratorConfig)
	if ac.GenRoot == "" {
		ac.GenRoot = "./gen"
	}
}

var mRegGenerator = make(map[string]Generator, 4)

func RegGenerator(generator Generator) {
	if _, ok := mRegGenerator[generator.Name()]; ok {
		panic("Generator already reg: " + generator.Name())
	}
	mRegGenerator[generator.Name()] = generator
}

var mGenerator = make(map[string]Generator, 4)

// 执行生成
func DoGenerate(ctx *Context) error {
	//加载生成器
	if err := loadGenerator(ctx); err != nil {
		return err
	}

	//执行生成
	for _, generator := range mGenerator {
		if err := generator.Generate(ctx); err != nil {
			return err
		}
	}

	return nil
}

func loadGenerator(ctx *Context) error {
	//按照配置的生成器名字, 构造对应的生成器
	for name := range GlobalConfig.Generator.Plugins {
		generator, ok := mRegGenerator[name]
		if !ok {
			return fmt.Errorf("generator %s not reg", name)
		}
		gen, err := generator.Make()
		if err != nil {
			return err
		}
		mGenerator[name] = gen
	}

	return nil
}
